﻿using fuzhu;
using LH.Models.APAR;
using LH.U8API.Bus; 
using Org.BouncyCastle.Asn1.Ocsp;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.GL;
using LH.Model.SA;
using ZDEntity;
using XXX.Models.AS;
using System.Diagnostics.Eventing.Reader;
using XXX.Models.WDFT;
using System.DirectoryServices.ActiveDirectory;
using System.Reflection;
using System.Security.Cryptography;
using System.Xml.Linq;
using MySqlConnector;
using XXX.Models.XXXEntities;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;

namespace Yonyou.U8.BO
{
    //取glmodel，为来源参照
    public class SaleOrderVM_KX : SaleOrder
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string xmlConfig { get; set; }
        public static string cDatabase = "";

        public SaleOrderVM_KX(Head head, List<Body> bodies) : base(head, bodies)
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }

       

        public  RetModel2 AddVerify()
        {
            try
            {
                string idcheck = "";
                
                string xmlconfig = XmlOperation.GetConfigXML();

                
                if (!SO_SOCO.AddVerifySaleOrder(this, xmlconfig, out string err, out string id, out string ccode))
                {
                    return DBService.ReErrObject("新增失败：" + err);
                }
                //else
                //{

                //    if (!SO_SOCO.OperateSaleOrder(id, "verify", out err))
                //    {
                //        //审核失败，需要删除数据
                //        SO_SOCO.OperateSaleOrder(id, "delete", out _);
                //        return DBService.ReErrObject("审核失败：" + err); ;
                //    }
                return DBService.ReOKObject(ccode);
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }



        }

        /// <summary>
        /// 销售订单 弃审并删除
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RetModel2 UnverifyDelete()
        {
            try
            {
                string ID = "";
                if (!Exists(ref ID))
                {
                    return DBService.ReOKObject("当前销售订单号已删除");
                }
                
                if (!SO_SOCO.OperateSaleOrder(ID, xmlConfig, "unverify,delete", out string err))
                {
                    return DBService.ReErrObject("弃审失败：" + err);
                }
                //else
                //{
                //    if (!SO_SOCO.OperateSaleOrder(ID, "delete", out err))
                //    {
                //        //删除失败,重新审核，保持原样
                //        SO_SOCO.OperateSaleOrder(ID, "verify", out _);
                //        return DBService.ReErrObject("删除失败：" + err);
                //    }
                return DBService.ReOKObject(head.csocode + "删除完成");
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }


        /// <summary>
        /// 销售订单 变更
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RetModel2  Change()
        {
            try
            {
                string idcheck = "";
                if (!Exists(ref idcheck))
                {
                    return DBService.ReErrObject("当前销售订单号不存在");
                }

                head.id = idcheck;
                string cRe = GetSaleOrderInfo();
                if (cRe != "ok")
                {
                    return DBService.ReErrObject("获取基础信息失败：" + cRe);
                }
                head.editprop = "M";
                //增加变更人
                //head.cchanger = head.cmaker;
                //head.dmoddate = head.ddate;


                //变更的处理， （1） 主键id，子表isosid写入（2）判断是新增，还是修改，还是删除 （3）时间戳读取

               
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    //取表头的时间戳
                    string sql = string.Format("select  cmaker,cverifier,  convert(char,convert(money,ufts),2) ufts from SO_SOMain where cSOCode = '{0}' ", head.csocode);
                    Head u8head = db.Ado.SqlQuery<Head>(sql).FirstOrDefault();

                    head.ufts = u8head.ufts;
                    //修改人更改
                    head.cchanger = head.cmaker;
                    head.cchangeverifier = head.cverifier;
                    head.dmoddate = DateTime.Now.ToString("yyyy-MM-dd");
                    head.dchangeverifydate = head.dmoddate;
                    head.cmaker = u8head.cmaker;
                    head.cverifier = u8head.cverifier;
                    head.id = idcheck;
                    //默认审核状态,没有勇
                    //head.istatus = "1";
                    //取表体信息,默认全部是D，循环后，剩余是D的，再写入表体
                    sql = string.Format("select 'D' AS editprop,  isosid,cdefine33, convert(char,convert(money,dufts),2) dufts  from SO_SODetails where id = '{0}' ", idcheck);

                    List<Body> u8bodies = db.Ado.SqlQuery<Body>(sql);
                    int bmodify = 0;//编辑标记
                    for (int i = 0; i < bodies.Count; i++)
                    {
                        bodies[i].id = idcheck;
                        bmodify = 0;
                        for (int j = 0; j < u8bodies.Count; j++)
                        {
                            if (bodies[i].cdefine33==u8bodies[j].cdefine33)
                            {
                                //表体不需要时间戳
                                //bodies[i].dufts = u8bodies[j].dufts;
                                bodies[i].isosid = u8bodies[j].isosid;
                                bodies[i].editprop ="M";
                                u8bodies[j].editprop = "M";
                                bmodify = 1;
                                continue;
                            }
                        }
                        if(bmodify==0)
                        {
                            bodies[i].editprop = "A";
                        }

                    }
                    //循环后检查删除的
                    for (int j = 0; j < u8bodies.Count; j++)
                    {
                        if (u8bodies[j].editprop == "D")
                        {
                            Body body = new Body();
                            body.id = idcheck;
                            body.editprop = "D";
                            //body.dufts = u8bodies[j].dufts;
                            body.isosid = u8bodies[j].isosid;
                            bodies.Add(body);
                        }
                    }

                }

                string err = "";
                if (!SO_SOCO.ChangeSaleOrder(this, xmlConfig, out err, out string id, out string ccode))
                {
                     
                    return DBService.ReErrObject("变更失败：" + err);
                }
               
                return DBService.ReOKObject("变更完成");
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }

        /// <summary>
        /// 完善销售订单信息,处理客户，金额，税率，辅助计量单位
        /// </summary>
        /// <returns></returns>
        public string GetSaleOrderInfo()
        {
            if (head == null)
            {
                return "Error: 没有数据";
            }
            if (bodies == null)
            {
                return "Error: 没有表体数据";
            }
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {


                string sqlFactory = "select top 1 cFactoryCode from Factory order by bDefaultFactory desc,cFactoryCode";
                string cFactoryCode = DbHelper.GetDbString(db.Ado.GetScalar(sqlFactory));



                Customer customer = db.Queryable<Customer>().Where(x => x.cCusCode == head.ccuscode).First();
                if (customer == null)
                {
                    return string.Format("Error: 客户编码{0}不存在", head.ccuscode);
                }
                else
                {
                    head.ccusname = customer.cCusName;
                    head.cinvoicecompany = customer.cInvoiceCompany;
                }

                #region  根据业务员取部门编码,不用
                //if(!string.IsNullOrWhiteSpace(head.cpersoncode))
                //{
                //    Person person =db.Queryable<Person>().Where(x => x.cPersonCode == head.cpersoncode).First();
                //    if (person == null)
                //    {
                //        return string.Format("Error: 业务员编码{0}不存在", head.cpersoncode);
                //    }
                //    else
                //    {
                //        head.cdepcode = person.cDepCode;                         
                //    }
                //}

                #endregion

                for (int i = 0; i < bodies.Count; i++)
                {
                    string cInvCode = bodies[i].cinvcode;
                    

                    #region 处理辅助计量单位
                  

                    //如果igrouptype！=0，则需要获取辅助单位换算率，并计算辅助数量
                    InvProperty invProperty = new InventoryVM().GetInvProperty(cInvCode,"", "");
                    if (invProperty == null)
                    {
                        return string.Format("第{0}行订单物料和{1}不存在", (i + 1).ToString(), cInvCode);
                    }
                    bodies[i].cgroupcode = invProperty.cGroupCode;
                    bodies[i].igrouptype = DbHelper.GetDbString(invProperty.iGroupType);
                    //iGroupType=0,无换算率，1,固定换算率，2,浮动换算率
                    if (invProperty.iGroupType != "0")
                    {
                        //辅助计量单位来源于来源单据，如果没有取库存单位
                          bodies[i].cunitid = invProperty.cSTComUnitCode;
                          bodies[i].iinvexchrate = invProperty.iChangRate;
                        if (DbHelper.GetDbdecimal(bodies[i].iinvexchrate) != 0)
                        {
                            bodies[i].inum = Math.Round(DbHelper.GetDbdecimal(bodies[i].iquantity) / DbHelper.GetDbdecimal(bodies[i].iinvexchrate), 6);

                        }
                          
                    }
                    
                    #endregion

                    #region 处理税率
                    //税率，先取客户档案，如果客户档案为空，币种是人民币的，默认税率是13

                    if (string.IsNullOrWhiteSpace(DbHelper.GetDbString(bodies[i].itaxrate)))
                    {
                        if (!string.IsNullOrWhiteSpace(DbHelper.GetDbString(customer.iCusTaxRate)))
                        {
                            bodies[i].itaxrate = DbHelper.GetDbdecimal(customer.iCusTaxRate);
                        }
                        //else if (!string.IsNullOrWhiteSpace(DbHelper.GetDbString(inv.iTaxRate)))
                        //{
                        //    bodies[i].itaxrate = DbHelper.GetDbdecimal(inv.iTaxRate);
                        //}
                        else if (head.cexch_name == "人民币")
                        {
                            //币种是人民币的，默认税率是13
                            bodies[i].itaxrate = 13;
                        }
                        else
                        {
                            bodies[i].itaxrate = 0;
                        }

                        if (i == 0)
                        {
                            head.itaxrate = DbHelper.GetDbString(bodies[i].itaxrate);
                        }
                    }

                    #endregion

                    #region 处理金额： 根据含税单价反算单价和无税单价，不用
                    //decimal dNatSum = DbHelper.GetDbdecimal(bodies[i].inatsum);  //本币含税金额
                    //decimal dOriSum = DbHelper.GetDbdecimal(bodies[i].isum);     //原币含税金额
                    //bodies[i].inatmoney = DbHelper.GetDbdecimal((dNatSum / (1 + DbHelper.GetDbdecimal(bodies[i].itaxrate) / 100)).ToString("F2"));
                    //bodies[i].imoney = DbHelper.GetDbdecimal((dOriSum / (1 + DbHelper.GetDbdecimal(bodies[i].itaxrate) / 100)).ToString("F2"));
                    //bodies[i].inattax = dNatSum - bodies[i].inatmoney;
                    //bodies[i].itax = dOriSum - bodies[i].imoney;
                    //bodies[i].itaxunitprice = Math.Round(dNatSum / bodies[i].iquantity, 6);
                    //bodies[i].inatunitprice = Math.Round(bodies[i].inatmoney / bodies[i].iquantity, 6);
                    //bodies[i].iunitprice = Math.Round(bodies[i].imoney / bodies[i].iquantity, 6);
                    //bodies[i].iquotedprice = bodies[i].itaxunitprice;
                    //bodies[i].idiscount = "0";
                    //bodies[i].kl = "100";
                    //bodies[i].kl2 = "100";
                    //bodies[i].bsaleprice = "1";
                    //bodies[i].bgift = "0";
                    #endregion
                    bodies[i].cfactorycode = cFactoryCode;



                }
            }
            
            return "ok";
        }

        /// <summary>
        /// 检查销售单号是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Exists(ref string id)
        {
            if (head == null)
            {
                return false;
            }
            
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                string sql = string.Format("select ID from SO_SOMain where cSOCode='{0}' ", head.csocode); 
                id = DbHelper.GetDbString(db.Ado.GetScalar(sql));

                 
                if (id == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
    
            } 
        
        }

        /// <summary>
        /// 销售订单 执行查询
        /// </summary>
        /// <returns></returns>
        public RetModel2 GetJinDu(string cSoCode)
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    string sql = string.Format("select cInvCode,cDefine33  as Bid ,iQuantity,iFHQuantity from  SO_Somain a, SO_SODetails  b where a.id =b.id and a.cSOCode = '{0}' ", cSoCode);
                    List<WDFT_SaleOrderJinDu.Item> lst = db.Ado.SqlQuery<WDFT_SaleOrderJinDu.Item>(sql);                   
                     if (lst.Count > 0)
                    {
                        WDFT_SaleOrderJinDu saleOrderJinDu = new WDFT_SaleOrderJinDu(cSoCode, lst);
                        return DBService.ReOKObject(saleOrderJinDu);
                    }
                    else
                    {
                        return DBService.ReErrObject("查询不到该单号的信息");
                    }
                }
                    
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }
    }
}
